/*
 * @Author: Haochen
 * @Date: 2021-12-25 10:37:13
 * @LastEditTime: 2021-12-26 14:34:06
 * @FilePath: \recipes-admin-system\src\store\modules\meals.js
 */

import api from '@/api/api.js';

export default {
  namespaced: true,
  state: {
    meals: [],
    total: 0,
    pageData: {
      pageSize: 0,
      currentPage: 1,
      pages: 0,
    },
  },
  mutations: {
    SET_MEALS(state, payload) {
      state.meals = payload;
      // Object.assign(state.admins, payload);
    },

    SET_TOTAL(state, payload) {
      state.total = payload;
    },

    SET_PAGESIZE(state, payload) {
      state.pageData.pageSize = payload;
    },

    SET_CURRENT(state, payload) {
      state.pageData.currentPage = payload;
    },

    SET_PAGES(state, payload) {
      state.pageData.pages = payload;
    },
  },
  getters: {
    mealsByPage: (state) => {
      let { currentPage, pages, pageSize } = state.pageData;
      //   console.log(currentPage, pages, pageSize);
      if (currentPage === pages) {
        // console.log(state.meals.slice((currentPage - 1) * pageSize));
        return state.meals.slice((currentPage - 1) * pageSize);
      }
      return state.meals.slice(
        (currentPage - 1) * pageSize,
        (currentPage - 1) * pageSize + pageSize
      );
    },
  },
  actions: {
    async getAllMealAsync(context, payload) {
      const { data: res } = await api.meals.getAllMeal();

      if (payload) {
        // console.log(payload);
        res.data = res.data.filter((item) => {
          if (JSON.stringify(item).indexOf(payload) !== -1) return item;
        });
      }
      if (res.meta.status === 200) {
        // console.log(res.data);
        context.commit('SET_MEALS', res.data);
        context.commit('SET_TOTAL', res.data.length);
        if (res.data.length % 4 === 0) {
          context.commit('SET_PAGES', res.data.length / 4);
        } else {
          context.commit('SET_PAGES', Math.ceil(res.data.length / 4));
        }

        return res.data;
      }
    },

    async getMealByIdAsync(context, payload) {
      const { data: res } = await api.meals.getAllMeal();

      if (payload) {
        // console.log(payload);
        res.data = res.data.filter((item) => {
          if (JSON.stringify(item).indexOf(payload) !== -1) return item;
        });
      }

      return res.data;
    },
  },
};
